/**
 * 路由预加载工具
 * 用于预加载关键路由组件，提升用户体验
 */

// 预加载关键路由
export const preloadCriticalRoutes = () => {
  // 预加载首页
  import("@/views/welcome/index.vue");

  // 预加载登录页
  import("@/views/login/index.vue");

  // 预加载布局组件
  import("@/layout/index.vue");
};

// 预加载常用组件
export const preloadCommonComponents = () => {
  // 预加载常用组件
  import("@/components/Wrapper");
  import("@/components/ReDialog/index.vue");
  import("@/components/Icon/src/SvgIcon.vue");
};

// 预加载工具函数
export const preloadUtils = () => {
  // 预加载常用工具函数
  import("@/utils/auth");
  import("@/utils/http/Axios");
  import("@/utils/tools/validate");
};

// 预加载样式
export const preloadStyles = () => {
  // 预加载关键样式
  import("@/style/index.scss");
  import("@/style/element-variarbles.scss");
};

// 智能预加载：根据用户行为预测需要加载的组件
export const smartPreload = (currentRoute: string) => {
  const routePreloadMap: Record<string, string[]> = {
    "/inventory": [
      "@/views/inventory/inventoryManage/index.vue",
      "@/views/inventory/inboundManage/index.vue",
      "@/views/inventory/outboundManage/index.vue"
    ],
    "/purchase": [
      "@/views/purchase/purchaseOrder/index.vue",
      "@/views/purchase/purchaseApply/index.vue",
      "@/views/purchase/purchaseInbound/index.vue"
    ],
    "/produce": [
      "@/views/produce/produceTask/index.vue",
      "@/views/produce/produceSale/index.vue",
      "@/views/produce/produceInbound/index.vue"
    ]
  };

  const routesToPreload = routePreloadMap[currentRoute] || [];

  routesToPreload.forEach(route => {
    // 使用动态导入预加载
    import(/* @vite-ignore */ route);
  });
};

// 初始化预加载
export const initPreload = () => {
  // 在浏览器空闲时预加载关键资源
  if ("requestIdleCallback" in window) {
    requestIdleCallback(() => {
      preloadCriticalRoutes();
      preloadCommonComponents();
      preloadUtils();
      preloadStyles();
    });
  } else {
    // 降级处理
    setTimeout(() => {
      preloadCriticalRoutes();
      preloadCommonComponents();
      preloadUtils();
      preloadStyles();
    }, 1000);
  }
};
